<template>
  <div>
    <ElTree
      ref="tree"
      class="mgb10"
      :data="manageTree"
      node-key="id"
      :props="options"
      default-expand-all
      show-checkbox
      :default-checked-keys="roleMenus"
    />
    <el-button type="primary" @click="submit(manageId, submitKeys)">保存权限</el-button>
  </div>
</template>

<script setup lang="ts">
  import { computed, PropType, ref } from 'vue'
  import { ElTree } from 'element-plus'
  import { Menu } from '@/types'

  const props = defineProps({
    manageId: {
      type: [String, Number],
      required: true,
    },
    manageData: {
      type: Array as PropType<string[]>,
      required: true,
    },
    manageTree: {
      type: Array as PropType<Menu[]>,
      required: true,
    },
    label: {
      type: String,
      required: false,
      default: 'label',
    },
    submit: {
      type: Function as PropType<(_id: string | number, _keys: (string | number)[]) => void>,
      required: true,
    },
  })

  //菜单树数据
  const manageTree = props.manageTree

  //非叶子节点
  const hasChildren = computed(() => {
    return manageTree
      .filter((item: Menu) => item.children && item.children.length > 0)
      .map(item => item.id)
  })
  //已选中的子节点数据
  const roleMenus = computed(() => {
    return props.manageData.filter(item => !hasChildren.value.includes(item))
  })

  const options = {
    label: props.label,
  }

  // 保存权限
  const tree = ref<InstanceType<typeof ElTree>>()
  //已选中的权限
  const submitKeys = computed(() => [
    ...tree.value!.getCheckedKeys(false),
    ...tree.value!.getHalfCheckedKeys(),
  ])
</script>

<style scoped></style>
